<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
        >
        <template slot="receiveTimeDTOSearch">
            <el-date-picker
              clearable
              v-model="dates2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </template>
        <template slot="searchMenu" slot-scope="{row,size}">
          <el-button :size="size" @click="()=>{searchFiledsEmpty(row);searchFiledsEmpty(searchForm)}" icon="el-icon-delete">清空</el-button>
        </template>
        <template slot-scope="scope" slot="menuLeft">
          <el-button type="primary" size="small" @click.stop="myAdd()">添加</el-button>
          <el-button type="primary" size="small" @click.stop="myInform()">通知</el-button>
          <el-upload
            class="upload-inline"
            action=""
            :show-file-list="false"
            accept=".xls,.xlsx"
            :http-request="handleImportDelivery"
          >
          <el-button type="primary" size="small">导入</el-button>
          </el-upload>
          <el-button type="primary" size="small" :hidden="true" v-if="false"  @click.stop="handleExport">导 出</el-button>
          <el-button type="primary" size="small" @click.stop="handleInputDetail()">入 库</el-button>
          <el-button type="primary" size="small" @click.stop="handleOutputDetail()">出 库</el-button>
          <el-button type="primary" size="small" :hidden="true" v-if="false" @click.stop="handlePrint">打 印</el-button>
        </template>
        <template slot="menuRight">
          <el-button
            @click="handleDownloadClickDelivery"
            type="text"
            size="small"
          >模板下载</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button :size="scope.size" :type="scope.type" v-if="scope.row.importFlag=='1' && permissionList.delBtn" @click="myDel(scope.row)">导入删除</el-button>
          <el-button :size="scope.size" :type="scope.type" v-if="scope.row.importFlag!='1' && permissionList.delBtn" @click="myDel(scope.row)">高级删除</el-button>
          <el-button :size="scope.size" :type="scope.type" v-if="scope.row.noticeStatus=='0'" @click="myEdit(scope.row)">编辑</el-button>
          <el-button :size="scope.size" :type="scope.type" @click="myApply(scope.row)">申诉</el-button>
          <el-button :size="scope.size" :type="scope.type" @click="myView(scope.row)">预览</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <open-dialog :DialogVisible.sync="addVisableDialog" title="新增" width="80%">
      <el-form label-width="60px" v-if="addVisableDialog">
        <avue-form v-model="formMy" ref="form" :option="formAdd" style="margin-bottom:40px;"></avue-form>
        <dynamic-crud title="配送明细信息" :data="tableDetail" :option="tableOptionDetailAdd"></dynamic-crud>
        <div class="bottom-menu-ticket-delivery">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="addVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
    <open-dialog :DialogVisible.sync="editVisableDialog" title="编辑" width="80%">
      <el-form label-width="60px" v-if="editVisableDialog">
        <avue-form v-model="formMy" ref="form" :option="formEdit" style="margin-bottom:40px;"></avue-form>
        <dynamic-crud title="配送明细信息" :data="tableDetail" :option="tableOptionDetailEdit"></dynamic-crud>
        <div class="bottom-menu-ticket-delivery">
          <el-button type="primary" @click="edit">保存</el-button>
          <el-button type="primary" @click="editVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
    <open-dialog :DialogVisible.sync="applyVisableDialog" title="申诉" width="80%">
      <el-form label-width="60px" v-if="applyVisableDialog">
        <div class="header" style="margin-bottom:15px;">配送摘要</div>
        <avue-form v-model="formMy" :option="formComplaintSend"></avue-form>
        <dynamic-crud
          title="配送明细信息"
          :data="tableDetail"
          :option="tableOptionDetailView"
          :button="false"
        ></dynamic-crud>
        <div class="header" style="margin-bottom:15px;margin-top:25px;">接收信息</div>
        <avue-form v-model="formMy1" :option="formComplaintReceive"></avue-form>
        <div class="header" style="margin-bottom:15px;">反馈信息</div>
        <avue-form v-model="formMy2" :option="formComplaintReturn"></avue-form>
        <div class="header" style="margin-bottom:15px;">申诉信息</div>
        <avue-form v-model="formMy3" :option="formComplaintApply"></avue-form>
        <div class="bottom-menu-ticket-delivery">
          <el-button type="primary" @click="apply">确认</el-button>
          <el-button type="primary" @click="applyVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
    <open-dialog :DialogVisible.sync="viewVisableDialog" title="预览" width="80%">
      <el-form label-width="60px" v-if="viewVisableDialog">
        <div class="header" style="margin-bottom:15px;">配送摘要</div>
        <avue-form v-model="formMy" :option="formView" style="margin-bottom:40px;"></avue-form>
        <dynamic-crud
          title="配送明细信息"
          :data="tableDetail"
          :option="tableOptionDetailView"
          :button="false"
        ></dynamic-crud>
        <div class="header" style="margin-bottom:15px;margin-top:25px;">接收信息</div>
        <avue-form v-model="formMy1" :option="formComplaintReceive" style="margin-bottom:40px;"></avue-form>
        <div class="header" style="margin-bottom:15px;">反馈信息</div>
        <avue-form v-model="formMy2" :option="formViewtReturn" style="margin-bottom:40px;"></avue-form>
        <div class="header" style="margin-bottom:15px;">申诉信息</div>
        <avue-form v-model="formMy3" :option="formViewApply" style="margin-bottom:40px;"></avue-form>
        <div class="bottom-menu-ticket-delivery">
          <el-button type="primary" @click="viewVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
  </div>
</template>

<script>
import baseCrud from '@/mixins/base-crud'
import {dateFormat} from '@/util/date'
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  getDetailObj,
  complain,
  inform,
  exportExcel,
  ImportDelivery,
  templateDelivery,
  inputDetailSubmit,
  outputDetailSubmit
} from "@/api/subway/swtkticketdelivery";
import {
  tableOption,
  formAdd,
  formEdit,
  formComplaintSend,
  formComplaintReceive,
  formComplaintReturn,
  formComplaintApply,
  formViewtReturn,
  formViewApply,
  formView,startDate, endDate,startDate2,endDate2
} from "@/const/crud/subway/swtkticketdelivery";
import {
  tableOptionDetailView,
  tableOptionDetailEdit,
  tableOptionDetailAdd,
} from "@/const/crud/subway/swtkticketdeliverydetail";
import { mapGetters } from "vuex";
import { handleExcelResponse } from "@/util/util";
import store from "@/store";
export default {
  name: "swtkticketdelivery",
  mixins: [baseCrud('subway/swtkticketdelivery')],
  data() {
    return {
      params: {
        dates2: [startDate2, endDate2]
      },
      dates2: '',
      searchForm: {
        dates1: [startDate, endDate],
        noticeStatus: '0'
      },
      addVisableDialog: false,
      editVisableDialog: false,
      applyVisableDialog: false,
      viewVisableDialog: false,
      formAdd: formAdd,
      formEdit: formEdit,
      formView: formView,
      formComplaintSend: formComplaintSend,
      formComplaintReceive: formComplaintReceive,
      formComplaintReturn: formComplaintReturn,
      formComplaintApply: formComplaintApply,
      formViewtReturn: formViewtReturn,
      formViewApply: formViewApply,
      tableOptionDetailView: tableOptionDetailView,
      tableOptionDetailEdit: tableOptionDetailEdit,
      tableOptionDetailAdd: tableOptionDetailAdd,
      tableDetail: [],
      formMy: {
        swTkTicketDeliveryDetails: [],
      },
      formMy1: {},
      formMy2: {},
      formMy3: {},
    };
  },
  watch: {
    'dates2':{
      handler(newValue, oldValue){
        if(this.validatenull(newValue)){
          this.params.dates2[0] = '';
          this.params.dates2[1] = '';
        }else{
          this.params.dates2[0] = dateFormat(newValue[0]).substr(0, 10);
          this.params.dates2[1] = dateFormat(newValue[1]).substr(0, 10);
        }
      }
    }
  },
  computed: {
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.st_sw_tk_ticket_delivery_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.st_sw_tk_ticket_delivery_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.st_sw_tk_ticket_delivery_edit,
          false
        ),
      };
    },
  },
  methods: {
    searchFiledsEmpty(form){
      this.dates2 = '';
      for (var i in form) {
        this.$delete(form,''+i+'')
      }
      this.getList(this.page);
    },
    myDel(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(row.id)
          .then(data => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },
    myInform() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("选中表数量不合法");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if(table.noticeStatus == "1"){
          this.$message.info("此数据已通知无需再次通知!");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认通知?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }).then(() => {
        inform(ids)
          .then(data => {
            if (data.data.code == "0") {
              this.$message.success("通知成功");
            }
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
      // inform(ids)
      //   .then((data) => {
      //     if (data.data.code == "0") {
      //       this.$message.success("通知成功");
      //     }
      //     this.getList(this.page);
      //   })
      //   .catch(() => {});
    },
    handleInputDetail:function(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
       if(table.isInstock=='1'){
	 this.$message.error("请检查选择的数据有已入库的数据，请重新选择！");
          return false;
	}
        ids.push(table.id);
      }
      this.$confirm("确认加入入库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        inputDetailSubmit(ids)
          .then(data => {
            this.$message.success("入库成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    handleOutputDetail:function(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if(table.isOutstock=='1'){
	  this.$message.error("请检查选择的数据有已出库的数据，请重新选择！");
          return false;
	}
	ids.push(table.id);
      }
      this.$confirm("确认加入出库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        outputDetailSubmit(ids)
          .then(data => {
            this.$message.success("出库成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    save() {
      this.$refs.form.validate(vaild=>{
        if(vaild){
          if(this.tableDetail.length==0){
            this.$message.info("请添加配送明细信息！");
            return;
          }else{
            for(const item of this.tableDetail){
              if(this.validatenull(item.ticketType) ||
                this.validatenull(item.ticketTypeParam) ||
                this.validatenull(item.deliveryCount)){
                  this.$message.info("票种、车票名称、配送/入张数为必填项！");
                  return;
              }
              // if(item.ticketTypeParam == 'PTDCP' && (item.ticketReturnType == null || item.ticketReturnType == undefined || item.ticketReturnType == '')) {
              //   this.$message.info("普通单程票必须选择车票种类");
              //   return;
              // }
            }
          }
          this.formMy.swTkTicketDeliveryDetails = this.tableDetail;
          addObj(this.formMy)
            .then((data) => {
              this.$message.success("添加成功");
              this.getList(this.page);
              this.addVisableDialog = false;
              done();
            })
            .catch(() => {});
        }
      })
    },
    myAdd() {
      this.formMy.dataSource = "0";
      this.addVisableDialog = true;
      this.tableDetail=[];
      this.formMy.deliveryTime = dateFormat(new Date())
      Object.keys(this.formMy).map(key => {this.formMy[key]=''})
      this.formMy.deliveryPersonName = this.$store.getters.userInfo.nikename
      this.formMy.deliveryPersonCode = this.$store.getters.userInfo.userCode
      this.formMy.deliveryPersonTwoName = this.$store.getters.userInfo.nikename
      this.formMy.deliveryPersonTwoCode = this.$store.getters.userInfo.userCode
      this.formMy.dataSource = '0'
    },

    myEdit(row) {
      getDetailObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formMy = res.swTkTicketDelivery;
          this.tableDetail = res.swTkTicketDeliveryDetails;
          this.tableDetail.forEach(plan => {
            plan.$cellEdit = true
          })
        })
        .then(() => {
          this.editVisableDialog = true;
        });
    },
    myApply(row) {
      getDetailObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formMy = res.swTkTicketDelivery;
          this.formMy1 = res.swTkTicketDelivery;
          this.formMy2 = res.swTkTicketDelivery;
          this.formMy3 = res.swTkTicketDelivery;
          this.tableDetail = res.swTkTicketDeliveryDetails;
        })
        .then(() => {
          this.applyVisableDialog = true;
        });
    },
    apply() {
      const fromSum = Object.assign(this.formMy, this.formMy3);
      this.formMy.lineSurveyResult = this.formMy2.lineSurveyResult;
      complain(this.formMy)
        .then((data) => {
          this.$message.success("申诉成功");
          this.getList(this.page);
          this.applyVisableDialog = false;
          done();
        })
        .catch(() => {});
    },
    myView(row) {
      getDetailObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formMy = res.swTkTicketDelivery;
          this.formMy1 = res.swTkTicketDelivery;
          this.formMy2 = res.swTkTicketDelivery;
          this.formMy3 = res.swTkTicketDelivery;
          this.tableDetail = res.swTkTicketDeliveryDetails;
        })
        .then(() => {
          this.viewVisableDialog = true;
        });
    },
    edit() {
      this.$refs.form.validate(vaild=>{
        if(vaild){
          if(this.tableDetail.length==0){
            this.$message.info("请添加配送明细信息！");
            return;
          }else{
            for(const item of this.tableDetail){
              if(this.validatenull(item.ticketType) ||
                this.validatenull(item.ticketTypeParam) ||
                this.validatenull(item.deliveryCount)){
                  this.$message.info("票种、车票名称、配送/入张数为必填项！");
                  return;
              }
              // if(item.ticketTypeParam == 'PTDCP' && (item.ticketReturnType == null || item.ticketReturnType == undefined || item.ticketReturnType == '')) {
              //   this.$message.info("普通单程票必须选择车票种类");
              //   return;
              // }
            }
          }
          this.formMy.swTkTicketDeliveryDetails = this.tableDetail;
          putObj(this.formMy)
            .then((data) => {
              this.$message.success("修改成功");
              this.getList(this.page);
              this.editVisableDialog = false;
              done();
            })
            .catch(() => {
              loading();
            });
        }
      })
    },
    async handleDownloadClickDelivery () {//车票配送信息导出模板
      this.uploading = true;
      try {
        const res = await templateDelivery();
        handleExcelResponse(res);
      } finally {
        this.uploading = false;
      }
    },
    handleImportDelivery(item) {//车票配送信息导入
      this.$message.info("正在导入，请耐心等待！");
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
      ImportDelivery(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000
        });
        this.getList(this.page);
      });
    },
  }
}
</script>

<style lang="scss">
.header {
  margin: 0 auto;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  border-bottom: none;
  background-color: #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom-menu-ticket-delivery {
  margin-top: 48px;
  text-align: center;
}
</style>
